package com.ad.pet.common.data.local;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.ad.pet.common.data.utils.FileUtil;
import com.ad.pet.common.data.utils.IOUtils;
import com.ad.pet.models.remote.MailList;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * Created by z on.
 * Des:
 * Date: 2017/3/13
 */

public class ContactsUtil {

    public static final String PHONE_BOOK_LABEL = "phonebook_label";
    /**
     * 需要查询的字段
     **/
    public static final String[] PHONES_PROJECTION = {ContactsContract.CommonDataKinds.Phone._ID,
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
            , ContactsContract.CommonDataKinds.Phone.NUMBER, PHONE_BOOK_LABEL};
    public static final int PHONES_ID = 0;
    /**
     * 联系人显示名称
     **/
    public static final int PHONES_DISPLAY_NAME_INDEX = 1;

    /**
     * 电话号码
     **/
    public static final int PHONES_NUMBER_INDEX = 2;


    Context mContext;
    FileUtil mFileUtil;

    @Inject
    public ContactsUtil(Context context, FileUtil fileUtil) {
        mContext = context;
        mFileUtil = fileUtil;
    }

    /**
     * 读取联系人
     *
     * @return
     * @throws Exception
     */
    public List<MailList> loadAll() throws Exception {
        List<MailList> mailLists = new ArrayList<>();
        ContentResolver mResolver =
                mContext.getContentResolver();

        Cursor cursor = mResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI
                , PHONES_PROJECTION, null, null, ContactsContract.CommonDataKinds.Phone.SORT_KEY_PRIMARY);
        readCursor(mailLists, cursor);
        return mailLists;
    }

    public void readCursor(List<MailList> mailLists, Cursor cursor) throws IOException {
        if (cursor != null) {
            while (cursor.moveToNext()) {
                String phone = cursor.getString(PHONES_NUMBER_INDEX);
                String name = cursor.getString(PHONES_DISPLAY_NAME_INDEX).replace("-", "").trim().replace(" ", "");
                Long contactId = cursor.getLong(PHONES_ID);
                String py = cursor.getString(cursor.getColumnIndex(PHONE_BOOK_LABEL));
                if (name != null && phone != null && contactId != null && !TextUtils.isEmpty(name) && !TextUtils.isEmpty(phone)) {
                    MailList mailList = new MailList(name, phone.replace("-","").replace(" ","").trim(), contactId);
                    if (py != null && !TextUtils.isEmpty(py)) mailList.setPy(py);
                    findImage(mailList, contactId);
                    mailLists.add(mailList);
                }

            }
        }
        if (cursor != null) cursor.close();
    }

//    public List<MailList> readCursor(Cursor data, List<MailList> mailLists) throws IOException {
//
//
//        while (data.moveToNext()) {
////            int id = data.getInt(0);
//            MailList mailList = new MailList();
//            Long contactId = data.getLong(data.getColumnIndex(ContactsContract.Contacts._ID));
//            String name = data.getString(1);
//            if (name != null && !TextUtils.isEmpty(name)) {
//                mailList.setName(name);
//                //查询电话号码
//                String phone = findPhone(contactId);
//                if (phone != null) {
//                    //查找头像
//                    mailList.setPhone(phone);
//                    findImage(mailList, contactId);
//                    mailLists.add(mailList);
//                }
//            }
//
//        }
//        if (data != null) data.close();
//        return mailLists;
//    }

    /**
     * 查找头像
     *
     * @param mailList
     * @param contactId
     * @throws IOException
     */
    private void findImage(MailList mailList, Long contactId) throws IOException {
        //获得contact_id的Uri
        Uri uriImage = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
        // 打开头像图片的InputStream     　　　　　　
        InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(mContext.getContentResolver(), uriImage);
        if (input != null) {
            File file = new File(mFileUtil.getIconDir().getPath(), mailList.getPhone() + ".jpg");
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            if (IOUtils.copyLarge(input, fileOutputStream) > 0) {
                mailList.setImagePath(file.getPath());
            }
        }
    }

    /**
     * 查找电话号码
     *
     * @param contactId
     * @return
     */
    @NonNull
    private String findPhone(Long contactId) {
        String phone = null;
        Cursor phones = mContext.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId, null, null);
        if (phones.moveToFirst()) {
            phone = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)).replace("-", "").replace(" ", "");

        }
        if (phones != null) phones.close();
        return phone;
    }

    /**
     * 根据电话号码删除联系人
     *
     * @param phone
     */
    public int deleteContactsByPhone(String phone) {
        ContentResolver resolver = mContext.getContentResolver();
        String[] pojection = {"contact_id"};
        Cursor query = resolver.query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                pojection, // Which columns to return.
                ContactsContract.CommonDataKinds.Phone.NUMBER + " = '"
                        + phone + "'", // WHERE clause.
                null, // WHERE clause value substitution
                null); // Sort order.

        if (query.getCount() > 0 && query.moveToFirst()) {
            String rawIdStr = query.getString(0);
            long rawId=Long.parseLong(rawIdStr);
            return resolver.delete(ContentUris.withAppendedId(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, rawId),
                    null, null);
        }

        return 0;
    }
}
